let moveClientX = 0;
let ttsUrl =
  "https://test.zhilingsd.com/tbdevcache/2a93f087dcaf4905848cf6d1afb3f042.wav";
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    audioSrc: {
      type: String,
    }, // 音频网址，非本地！
    audioCoverUrl: {
      type: String,
    }, // 音频网址，非本地！

    
  },

  /**
   * 组件的初始数据
   */
  data: {
    audioInfo:{},
    isPlay: false, // 播放中
    total: "00:00", // 音频总长度
    totalToNumber: 0,
    progress: "00:00", // 播放进度
    progressWidth: 0, // 进度条的长度
    innerAudioContext: null, // 音频对象
    x: 0, // 滑块x坐标
    isTouchMove: false, // 拖拽时显示
    isCanplay: false, // 监听音频进入可以播放状态的事件
    isProgress: false, // 是否显示播放的进度
    checkAudioDurationTime: "",
  },
  ready() {
    this.getDom(".audio__progress", (res) => {
      this.getDom(".audio__progress_bar", (val) => {
        this.setData({
          progressWidth: res[0].width - val[0].width,
        });
        console.log("res=", res, ";progressWidth=", this.data.progressWidth);
      });
    });
    //this.initAudio();
    
  },
  /**
   * @description: 页面离开时销毁音频
   */
  detached() {
    //this.data.innerAudioContext.destroy();
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // destroy() {
    //   this.data.innerAudioContext.destroy();
    // },
    initAudio(info) {
      console.log('initAudio',info)
      this.data.audioInfo = info;
      this._createAudio()
    },
    _createAudio(){
      this.data.innerAudioContext = wx.getBackgroundAudioManager();
      this.data.innerAudioContext.title = this.data.audioInfo.audioChapterName;
      this.data.innerAudioContext.src = this.data.audioInfo.ttsUrl;
      this.data.innerAudioContext.coverImgUrl = this.data.audioCoverUrl;
      this._audioEventListen()
      this._initProgress();
    },
    _initProgress(value) {
      this.setData({
        //初始化进度条
        isPlay: false,
        progress: value ? this.getTime(value) : "00:00",
        totalToNumber: 0,
        isCanplay: false,
        x: 0,
      });
    },
    _audioEventListen() {
      if (!this.data.innerAudioContext) return;
      //仅IOS
      this.data.innerAudioContext.onNext((res) => {
        this.triggerEvent("audioOnNextEvent");
      });
      //仅IOS
      this.data.innerAudioContext.onPrev((res) => {
        this.triggerEvent("audioOnPrevEvent");
      });
      //暂停监控
      this.data.innerAudioContext.onPause((res) => {
        this.triggerEvent("audioOnPauseEvent");
      });
      //暂停监控
      this.data.innerAudioContext.onStop((res) => {
        console.log('this.triggerEvent("audioOnStopEvent"')
        this.triggerEvent("audioOnStopEvent");
        this.data.innerAudioContext = ''
        this.setData({
          x: 0,
        });
      });



      // 监听音频播放进度更新事件
      this.data.innerAudioContext.onTimeUpdate(() => {
        let value = this.data.innerAudioContext.currentTime;
        // this.setData({
        //   progress: this.getTime(value),
        // });
        this.changeX(value);
      });

      this.data.innerAudioContext.onPlay((res) => {
        var duration = this.data.innerAudioContext.duration; // 这行代码非常重要！注释后，切换播放和暂停时会出现异常
        this.checkAudioDuration(); //获取播放时长
        this.triggerEvent("audioOnPlayEvent");
      });

      // 监听音频进入可以播放状态的事件
      this.data.innerAudioContext.onCanplay(() => {
        console.log("onCanplay");
        if (this.data.isCanplay) return;
        this.setData({
          isPlay: true,
          x: 0,
          isCanplay: true,
          isProgress: true,
        });
        this.checkAudioDuration();
      });

      // 监听音频完成跳转的操作
      // this.data.innerAudioContext.onSeeked((res) => {
      //   this.goPlay();
      // });
      // 播放结束后
      this.data.innerAudioContext.onEnded((res) => {
        //this.data.innerAudioContext.seek(0); // 开启后会无限循环播放
        //this.initProgress()
        this.triggerEvent("audioOnEndEvent");
      });

      this.data.innerAudioContext.onError((res) => {
        console.log(res.errMsg, res.errCode);
      });
    },
    setSeek(value) {
      this.data.innerAudioContext.seek(value);
      this.initProgress(value);
    },
    checkAudioDuration() {
      clearTimeout(this.data.checkAudioDurationTime);
      this.data.checkAudioDurationTime = setTimeout(() => {
        if (!this.data.innerAudioContext.duration) {
          //!NaN === true
          this.checkAudioDuration();
        } else {
          if (this.data.totalToNumber === 0) {
            this.setData({
              total: this.getTime(this.data.innerAudioContext.duration),
              totalToNumber: this.data.innerAudioContext.duration,
            });
          }
        }
      }, 200);

      console.log(this.data);
    },
    goPlay() {
      this.audioPlay();
    },
    goPause() {
      this.audioPause();
    },
    audioPlay() {
      this.data.innerAudioContext.play();
      this.setData({
        isPlay: true,
      });
      setTimeout(() => {
        console.log(this.data.innerAudioContext.paused);
      }, 100);
    },
    audioPause() {
      this.data.innerAudioContext.pause();
      this.setData({
        isPlay: false,
      });
      console.log(
        "暂停,currentTime =",
        this.data.innerAudioContext.currentTime
      );
    },
    getDom(name, callback) {
      let query = wx.createSelectorQuery().in(this);
      query.select(name).boundingClientRect();
      query.exec((res) => {
        callback && callback(res);
      });
    },
    bindchange(e) {
      //if(isAudioUpdate) return;
      let { x, y } = e.detail;
      let progress = (x / this.data.progressWidth) * this.data.totalToNumber;
      this.setData({
        progressDefault: progress,
        progress: this.getTime(progress),
      });
      //this.changeX(this.data.progressDefault)
    },
    touchMove(e) {
      this.setData({
        isTouchMove: true,
      });
    },
    touchStart() {
      this.checkAudioDuration(); //获取播放时长
      this.data.innerAudioContext.pause();
    },
    touchEnd() {
      this.data.innerAudioContext.seek(this.getTime(this.data.progress, "", 1));
      this.changeX(this.data.progressDefault);
      if (this.data.isPlay) {
        setTimeout(() => {
          this.goPlay();
        }, 100);
      }
      this.setData({
        isTouchMove: false,
      });
    },
    changeX(value) {
      let newValue = (
        (this.getTime(value, "", 1) / this.data.totalToNumber) *
        this.data.progressWidth
      ).toFixed(2);
      this.setData({
        x: Number(newValue),
      });
    },
    getTime(value, isHours, type) {
      let result = null;
      let hours = 0;
      let minute = 0;
      let second = 0;
      // 时间转数字
      if (type) {
        const newValue = ("" + value).split(":");
        if (newValue.length === 3) {
          hours = newValue[0] * 60 * 60;
          minute = newValue[1] * 60;
          second = newValue[2];
        } else if (newValue.length === 2) {
          minute = newValue[0] * 60;
          second = newValue[1];
        } else if (newValue.length === 1) {
          second = newValue[0];
        }
        result = hours + minute + Number(second);
      } else {
        // 数字转时间
        minute = Math.floor(value / 60);
        second = Math.floor(value % 60);
        // 分
        if (minute < 10) {
          minute = "0" + minute;
        }
        // 秒
        if (second < 10) {
          second = "0" + second;
        }
        // 输出小时
        if (isHours) {
          hours = Math.floor(value / 3600);
          // 时
          if (hours < 10) {
            hours = "0" + hours;
          }
          result = hours + ":" + minute + ":" + second;
        } else {
          result = minute + ":" + second;
        }
      }
      return result;
    },
  },
});
